<template>
  <div class="tab-navigation">
    <!-- 页签按钮 -->
    <div class="tab-nav" ref="tabNavRef">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', { active: currentTab === index }]"
        @mousedown="onMouseDown(index, $event)"
      >
        <button
          class="tab-button"
          :class="{ active: currentTab === index }"
          @click="selectTab(index)"
          @contextmenu.prevent="showContextMenu($event, index)"
        >
          {{ tab.title }}
          <!-- 控制关闭按钮的显示 -->
          <span v-if="!(tab.fullPath === getHomePage().path)" class="close-tab" @click.stop="removeTab(index)">×</span>
        </button>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div
      v-if="contextMenu.visible"
      class="context-menu"
      :style="{ top: contextMenu.top + 'px', left: contextMenu.left + 'px' }"
    >
      <ul>
        <li @click="handleContextMenuAction('refresh')">刷新</li>
        <li @click="handleContextMenuAction('close')">关闭</li>
        <li @click="handleContextMenuAction('closeOthers')">关闭其他</li>
        <li @click="handleContextMenuAction('closeAll')">关闭所有</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
import { getMenuMap, getHomePage } from '@/utils/index'
const { proxy } = getCurrentInstance()
const route = useRoute() // 获取当前路由对象

// 定义页签数据
const tabs = ref([])

// 当前选中的页签索引
const currentTab = ref(0)

// 拖拽相关变量
const isDragging = ref(false) // 是否正在拖拽
const startX = ref(0) // 鼠标按下时的初始位置

// 右键菜单状态
const contextMenu = ref({
  visible: false,
  top: 0,
  left: 0,
  tabIndex: null // 当前右键点击的页签索引
})

// 切换页签
const selectTab = index => {
  currentTab.value = index
  const selectItem = tabs.value[index]
  proxy.$ToPath(selectItem.fullPath)
}

// 添加页签
const addTab = item => {
  const tabIndex = tabs.value.findIndex(v => v.fullPath === item.fullPath)
  if (tabIndex >= 0) {
    currentTab.value = tabIndex
  } else {
    tabs.value.push({
      name: item.name,
      title: item.label,
      fullPath: item.fullPath
    })
    currentTab.value = tabs.value.length - 1 // 自动切换到新页签
  }
}

// 删除页签
const removeTab = index => {
  // if (tabs.value[index].fullPath === getHomePage().path) {
  //   return
  // }
  tabs.value.splice(index, 1)
  if (tabs.value.length === 0) {
    proxy.$ToPath('/') // 如果只剩下一个页签，直接跳转到首页
    return
  }
  if (currentTab.value === index) {
    selectTab(Math.max(0, index - 1)) // 切换到前一个页签
  }
}

// 显示右键菜单
const showContextMenu = (event, index) => {
  event.preventDefault() // 阻止默认右键菜单
  contextMenu.value = {
    visible: true,
    top: event.clientY,
    left: event.clientX,
    tabIndex: index
  }

  // 点击页面其他地方隐藏右键菜单
  document.addEventListener('click', hideContextMenu)
}

// 隐藏右键菜单
const hideContextMenu = () => {
  contextMenu.value.visible = false
  document.removeEventListener('click', hideContextMenu)
}

// 处理右键菜单操作
const handleContextMenuAction = action => {
  const index = contextMenu.value.tabIndex
  hideContextMenu()

  switch (action) {
    case 'refresh':
      refreshTab(index)
      break
    case 'close':
      removeTab(index)
      break
    case 'closeOthers':
      closeOtherTabs(index)
      break
    case 'closeAll':
      closeAllTabs()
      break
    default:
      break
  }
}

// 刷新页签
const refreshTab = index => {
  const tab = tabs.value[index]
  proxy.$emit('reShow', tab)
  if (tab.fullPath === tabs.value[currentTab.value].fullPath) {
  } else {
    proxy.$ToPath(tab.fullPath) // 跳转到该页签以触发刷新
  }
}

// 关闭其他页签
const closeOtherTabs = index => {
  const tab = tabs.value[index]
  tabs.value = [tab]
  currentTab.value = 0
  proxy.$ToPath(tab.fullPath) // 跳转到该页签
}

// 关闭所有页签
const closeAllTabs = () => {
  tabs.value = []
  proxy.$ToPath('/') // 跳转到首页
}

// 保存页签数据到 sessionStorage
const saveTabsToSessionStorage = () => {
  sessionStorage.setItem('tabs', JSON.stringify(tabs.value))
  sessionStorage.setItem('currentTab', currentTab.value)
}

// 从 sessionStorage 加载页签数据
const loadTabsFromSessionStorage = () => {
  // 读取保存的页签数据和当前选中的页签
  const savedTabs = sessionStorage.getItem('tabs')
  const savedCurrentTab = sessionStorage.getItem('currentTab')

  if (savedTabs) {
    // 将保存的页签数据解析为对象
    tabs.value = JSON.parse(savedTabs)

    // 如果有页签数据且存在当前选中的页签，则选中对应的页签
    if (tabs.value.length > 0 && savedCurrentTab !== null) {
      selectTab(parseInt(savedCurrentTab, 10))
    }

    // 删除 sessionStorage 中的数据
    sessionStorage.removeItem('tabs')
    sessionStorage.removeItem('currentTab')
  }
}

// 监听路由变化
watch(
  () => route.path, // 监听路由的 fullPath 变化
  newPath => {
    const menuItem = getMenuMap().get(newPath)
    const newTab = {
      name: route.name,
      label: menuItem?.label || route.meta?.title || route.name, // 优先使用 meta.title，否则使用 name
      fullPath: newPath
    }
    addTab(newTab)
    saveTabsToSessionStorage()
    proxy.$emit('addTab', newTab)
  },
  { immediate: true } // 关键配置：初始化时立即执行一次
)
// const handleBeforeUnload = event => {
//   saveTabsToSessionStorage()
// }
onMounted(() => {
  // window.addEventListener('beforeunload', handleBeforeUnload)
  loadTabsFromSessionStorage()
  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
})

onBeforeUnmount(() => {
  // window.removeEventListener('beforeunload', handleBeforeUnload)
  document.removeEventListener('mousemove', onMouseMove)
  document.removeEventListener('mouseup', onMouseUp)
})

// 鼠标按下事件
const onMouseDown = (index, event) => {
  if (event.button === 0) {
    // 左键逻辑：执行拖拽相关操作
    currentTab.value = index
    isDragging.value = true
    startX.value = event.clientX
  }
}

// 鼠标移动事件
const onMouseMove = event => {
  if (!isDragging.value) return
  const currentIndex = currentTab.value
  const newIndex = calculateNewIndex(event.clientX)

  if (currentIndex !== newIndex) {
    // 动态调整页签顺序
    const draggedTab = tabs.value[currentIndex]
    tabs.value.splice(currentIndex, 1) // 移除被拖拽的页签
    tabs.value.splice(newIndex, 0, draggedTab) // 插入到目标位置
    currentTab.value = newIndex // 更新拖拽索引
  }
}

// 鼠标释放事件
const onMouseUp = () => {
  if (isDragging.value) {
    isDragging.value = false
  }
}

// 计算新的索引
const calculateNewIndex = clientX => {
  const tabElements = Array.from(document.querySelectorAll('.tab-item'))
  for (let i = 0; i < tabElements.length; i++) {
    const rect = tabElements[i].getBoundingClientRect()
    if (clientX >= rect.left && clientX <= rect.right) {
      return i
    }
  }
  return currentTab.value
}
</script>

<style scoped>
/* 原有样式保持不变 */
.tab-navigation {
  height: 30px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.tab-nav {
  display: flex;
  gap: 5px;
}

.tab-item {
  position: relative;
}

.tab-button {
  height: 30px;
  padding: 5px 12px;
  font-size: 14px;
  cursor: pointer;
  background-color: #eee;
  border: none;
  border-radius: 4px 4px 0 0;
  transition: background-color 0.3s ease, padding-right 0.3s ease; /* 添加 padding-right 的过渡效果 */
  white-space: nowrap; /* 核心属性，兼容所有现代浏览器及旧浏览器 */
  position: relative; /* 确保子元素可以使用绝对定位 */
}

.tab-button.active {
  padding-right: 30px; /* 增加右侧内边距以容纳关闭按钮 */
  background-color: #c8c8c8;
}

.tab-button:hover {
  padding-right: 30px; /* 增加右侧内边距以容纳关闭按钮 */
  background-color: #c8c8c8;
}

.close-tab {
  display: none; /* 默认隐藏 */
  margin-left: 5px;
  color: #fff; /* 文字颜色改为白色 */
  background-color: #ff4d4f; /* 背景颜色改为红色 */
  border-radius: 50%; /* 圆形按钮 */
  width: 16px;
  height: 16px;
  text-align: center;
  line-height: 16px;
  cursor: pointer;
  position: absolute; /* 绝对定位 */
  right: 5px; /* 固定距离右侧边缘 5px */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 精确垂直居中 */
  transition: opacity 0.3s ease;
}

.tab-button.active > .close-tab {
  display: block; /* 鼠标悬停时显示 */
}

.tab-button:hover > .close-tab {
  display: block; /* 鼠标悬停时显示 */
}

/* 新增右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  padding: 5px 0;
}

.context-menu ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.context-menu li {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.context-menu li:hover {
  background-color: #f0f0f0;
}
</style>